<?php
namespace Admin\Controller;

use Think\Page;
use Think\Verify;
use Think\Db;
use Think\Exception;
use Think\Log;

class ImportController extends BaseController {
    public function _initialize()
    {
        ini_set('max_execution_time','0');
    }
    /**
     * 导入users
     */
    public function saveUsers()
    {
        $data = M('account_info','xbt_')->alias('a')
        ->field('a.*,b.YL2 xianlu,b.LINE_TYPE,b.address,b.PROVINCE_ID,b.CITY_ID,b.COUNTY_ID,c.AREA_NAME as province,d.AREA_NAME as city,e.AREA_NAME as county')
        ->join('xbt_account_client as b on b.ACCOUNT_ID=a.ACCOUNT_ID')
        ->join('xbt_area_code as c on c.ID=b.PROVINCE_ID')
        ->join('xbt_area_code as d on d.ID=b.CITY_ID')
        ->join('xbt_area_code as e on e.ID=b.COUNTY_ID')
        ->where(array('a.ACCOUNT_TYPE'=>'Client'))->select();
        // exit(M()->getLastSql());
        // exit(json_encode($data));
        if($data){
            $errorNo = [];
            try{
                Db::startTrans(); //开启事务
                $insert = [];
                foreach($data as $item){
                    if($item && $item['account_id']){ //有数据才添加
                        $insert[] = [
                            'user_id'=>$item['account_id'],
                            'email'=>'',
                            'password'=>$item['password'],
                            'sex'=>'',
                            'birthday'=>'',
                            'user_money'=>$item['money'],
                            'frozen_money'=>'',
                            'distribut_money'=>'',
                            'pay_points'=>'',
                            'address_id'=>'',
                            'reg_time'=>$item['create_time']?strtotime($item['create_time']):null,
                            'last_login'=>$item['last_login_time']?strtotime($item['last_login_time']):null,
                            'qq'=>'',
                            'mobile'=>$item['account'],
                            'mobile_validated'=>'',
                            'oauth'=>'',
                            'openid'=>$item['gzh_openid'],
                            'open_id'=>$item['openid'],
                            'unionid'=>$item['unionid'],
                            'head_pic'=>'',
                            'quyu'=>'',
                            'level'=>'',
                            'discount'=>'',
                            'total_amount'=>'',
                            'is_lock'=>$item['status']==1 ? 0 : 1,
                            'is_distribut'=>'',
                            'first_leader'=>'',
                            'parent_id'=>'',
                            'second_leader'=>'',
                            'third_leader'=>'',
                            'token'=>'',
                            'gender'=>'',
                            'nick_name'=>'',
                            'nickname'=>$item['account_name'],
                            'biaoshi'=>$item['line_type']==1?'快线':'普通',
                            'biaoshi_xian'=>$item['xianlu'],
                            'company'=>$item['account_name'],
                            'company_address'=>$item['city'].$item['county'].$item['address'],
                            'store_id'=>'',
                            'keep_sign_day'=>'',
                            'xsort'=>'',
                            'fenbu_id'=>'',
                            'zp_cishu'=>'',
                            'salesman'=>'',
                            'fast_flag'=>$item['line_type'],
                            'salt'=>$item['salt'],
                            'xbt_user_id'=>$item['account_id'],
                        ];
                    }
                }
                // exit(json_encode($insert));
                $res = M('users')->addAll($insert);
                dump($res);
                Db::commit(); //事务提交
                exit('success');
            }catch(Exception $e){
                Db::rollback();//事务回滚
                Log::record($e->getMessage(),'ERR');
                $errorNo[] = $item[0];
            }

        }
        exit;
    }
    
    public function updateUsers()
    {
        
        $data = M('account_info','xbt_')->where(array('ACCOUNT_TYPE'=>'Client'))->order('ACCOUNT_ID ASC')->select();
        // exit(M()->getLastSql());
        echo(json_encode($data));exit;
        if($data){
            $errorNo = [];
            try{
                Db::startTrans(); //开启事务
                foreach($data as $item){
                    if($item && $item['account_id']){ //有数据才添加
                        // $client = M('account_info','xbt_')->where(array('ACCOUNT_ID'=>$item['account_id']))->find();
                        M('seller')->where(['xbt_supplier_id'=>$item['account_id']])->save(['seller_name'=>$item['account']]);
                    }
                }
                // exit(json_encode($insert));
                Db::commit(); //事务提交
                exit('success');
            }catch(Exception $e){
                Db::rollback();//事务回滚
                Log::record($e->getMessage(),'ERR');
                $errorNo[] = $item[0];
            }

        }
        exit;
    }

    function saveDriver() {
        $data = M('account_info','xbt_')->where(array('ACCOUNT_TYPE'=>'Driver'))->select();
        // exit(M()->getLastSql());
        dump(count($data));
        // exit(json_encode($data));
        if($data){
            $errorNo = [];
            try{
                Db::startTrans(); //开启事务
                $insert = [];
                foreach($data as $item){
                    if($item && $item['account_id']){ //有数据才添加
                        $insert = [
                            'user_id'=>$item['account_id'],
                            'email'=>'',
                            'password'=>$item['password'],
                            'sex'=>'',
                            'birthday'=>'',
                            'user_money'=>$item['money'],
                            'frozen_money'=>'',
                            'distribut_money'=>'',
                            'pay_points'=>'',
                            'address_id'=>'',
                            'reg_time'=>$item['create_time']?strtotime($item['create_time']):null,
                            'last_login'=>$item['last_login_time']?strtotime($item['last_login_time']):null,
                            'qq'=>'',
                            'mobile'=>$item['account'],
                            'mobile_validated'=>'',
                            'oauth'=>'',
                            'openid'=>$item['gzh_openid'],
                            'open_id'=>$item['openid'],
                            'unionid'=>$item['unionid'],
                            'head_pic'=>'',
                            'quyu'=>'',
                            'level'=>'',
                            'discount'=>'',
                            'total_amount'=>'',
                            'is_lock'=>$item['status']==1 ? 0 : 1,
                            'is_distribut'=>'',
                            'first_leader'=>'',
                            'parent_id'=>'',
                            'second_leader'=>'',
                            'third_leader'=>'',
                            'token'=>'',
                            'gender'=>'',
                            'nick_name'=>'',
                            'nickname'=>'',
                            'biaoshi'=>'',
                            'biaoshi_xian'=>'',
                            'company'=>$item['account_name'],
                            'company_address'=>'',
                            'store_id'=>'',
                            'keep_sign_day'=>'',
                            'xsort'=>'',
                            'fenbu_id'=>'',
                            'zp_cishu'=>'',
                            'salesman'=>'',
                            'is_driver'=>1,
                            'fast_flag'=>'',
                            'xbt_user_id'=>$item['account_id'],
                        ];
                        $count = M('users')->where(array('mobile'=>$item['account']))->count();
                        
                        if($count==0){
                            $res = M('users')->data($insert)->add();
                        }else{
                            $res = M('users')->where(array('mobile'=>$item['account']))->save(array('is_driver'=>1,'xbt_driver_id'=>$item['account_id']));
                        }
                        dump($res);
                    }
                }
                Db::commit(); //事务提交
                exit('success');
            }catch(Exception $e){
                Db::rollback();//事务回滚
                Log::record($e->getMessage(),'ERR');
                $errorNo[] = $item[0];
            }
        }
        exit;
    }
    function saveSales() {
        $data = M('account_info','xbt_')->where(array('ACCOUNT_TYPE'=>'Sales'))->select();
        // exit(M()->getLastSql());
        // dump(count($data));exit;
        // exit(json_encode($data));
        if($data){
            $errorNo = [];
            try{
                Db::startTrans(); //开启事务
                $insert = [];
                foreach($data as $item){
                    if($item && $item['account_id']){ //有数据才添加
                        $insert = [
                            'user_id'=>$item['account_id'],
                            'email'=>'',
                            'password'=>$item['password'],
                            'sex'=>'',
                            'birthday'=>'',
                            'user_money'=>$item['money'],
                            'frozen_money'=>'',
                            'distribut_money'=>'',
                            'pay_points'=>'',
                            'address_id'=>'',
                            'reg_time'=>$item['create_time']?strtotime($item['create_time']):null,
                            'last_login'=>$item['last_login_time']?strtotime($item['last_login_time']):null,
                            'qq'=>'',
                            'mobile'=>$item['account'],
                            'mobile_validated'=>'',
                            'oauth'=>'',
                            'openid'=>$item['gzh_openid'],
                            'open_id'=>$item['openid'],
                            'unionid'=>$item['unionid'],
                            'head_pic'=>'',
                            'quyu'=>'',
                            'level'=>'',
                            'discount'=>'',
                            'total_amount'=>'',
                            'is_lock'=>$item['status']==1 ? 0 : 1,
                            'is_distribut'=>'',
                            'first_leader'=>'',
                            'parent_id'=>'',
                            'second_leader'=>'',
                            'third_leader'=>'',
                            'token'=>'',
                            'gender'=>'',
                            'nick_name'=>'',
                            'nickname'=>'',
                            'biaoshi'=>'',
                            'biaoshi_xian'=>'',
                            'company'=>$item['account_name'],
                            'company_address'=>'',
                            'store_id'=>'',
                            'keep_sign_day'=>'',
                            'xsort'=>'',
                            'fenbu_id'=>'',
                            'zp_cishu'=>'',
                            'salesman'=>1,
                            'is_driver'=>'',
                            'fast_flag'=>'',
                            'xbt_user_id'=>$item['account_id'],
                        ];
                        $count = M('users')->where(array('mobile'=>$item['account']))->count();
                        
                        if($count==0){
                            $res = M('users')->data($insert)->add();
                        }else{
                            $res = M('users')->where(array('mobile'=>$item['account']))->save(array('salesman'=>1,'xbt_sales_id'=>$item['account_id']));
                        }
                        dump($res);
                    }
                }
                Db::commit(); //事务提交
                exit('success');
            }catch(Exception $e){
                Db::rollback();//事务回滚
                Log::record($e->getMessage(),'ERR');
                $errorNo[] = $item[0];
            }
        }
        exit;
    }

    public function saveStore(){
        $data = M('account_info','xbt_')->where(array('ACCOUNT_TYPE'=>'Supplier'))->select();
        // exit(M()->getLastSql());
        // dump(count($data));exit;
        // exit(json_encode($data));
        if($data){
            $errorNo = [];
            try{
                Db::startTrans(); //开启事务
                $insert = [];
                foreach($data as $item){
                    if($item && $item['account_id']){ //有数据才添加
                        $insert = [
                            'user_id'=>$item['account_id'],
                            'email'=>'',
                            'password'=>$item['password'],
                            'sex'=>'',
                            'birthday'=>'',
                            'user_money'=>$item['money'],
                            'frozen_money'=>'',
                            'distribut_money'=>'',
                            'pay_points'=>'',
                            'address_id'=>'',
                            'reg_time'=>$item['create_time']?strtotime($item['create_time']):null,
                            'last_login'=>$item['last_login_time']?strtotime($item['last_login_time']):null,
                            'qq'=>'',
                            'mobile'=>$item['account'],
                            'mobile_validated'=>'',
                            'oauth'=>'',
                            'openid'=>$item['gzh_openid'],
                            'open_id'=>$item['openid'],
                            'unionid'=>$item['unionid'],
                            'head_pic'=>'',
                            'quyu'=>'',
                            'level'=>'',
                            'discount'=>'',
                            'total_amount'=>'',
                            'is_lock'=>$item['status']==1 ? 0 : 1,
                            'is_distribut'=>'',
                            'first_leader'=>'',
                            'parent_id'=>'',
                            'second_leader'=>'',
                            'third_leader'=>'',
                            'token'=>'',
                            'gender'=>'',
                            'nick_name'=>'',
                            'nickname'=>$item['account_name'],
                            'biaoshi'=>'',
                            'biaoshi_xian'=>'',
                            'company'=>$item['account_name'],
                            'company_address'=>'',
                            'store_id'=>'',
                            'keep_sign_day'=>'',
                            'xsort'=>'',
                            'fenbu_id'=>'',
                            'zp_cishu'=>'',
                            'salesman'=>1,
                            'is_driver'=>'',
                            'fast_flag'=>'',
                            'salt'=>$item['salt'],
                            'xbt_user_id'=>$item['account_id'],
                            'xbt_supplier_id'=>$item['account_id'],
                        ];
                        $count = M('users')->where(array('mobile'=>$item['account']))->count();
                        if($count==0){
                            $id = M('users')->add($insert);
                        }else{
                            $id = M('users')->where(array('mobile'=>$item['account']))->getField('user_id');
                            M('users')->where(array('user_id'=>$id))->save([
                                'openid'=>$item['gzh_openid'],
                                'xbt_supplier_id'=>$item['account_id'],
                                'password'=>$item['password'],
                                'salt'=>$item['salt'],
                            ]);
                        } 
                        $supplier = M('account_supplier','xbt_')->alias('a')
                        ->field('a.*,c.AREA_NAME as province,d.AREA_NAME as city,e.AREA_NAME as county')
                        ->join('xbt_area_code as c on c.ID=a.PROVINCE_ID','left')
                        ->join('xbt_area_code as d on d.ID=a.CITY_ID','left')
                        ->join('xbt_area_code as e on e.ID=a.COUNTY_ID','left')
                        ->where(['a.ACCOUNT_ID'=>$item['account_id']])->find();
                        dump($item['account_id']);
                        dump($supplier);
                        $store = [
                            'store_id'=>$item['account_id'],
                            'store_name'=>$supplier['supplier_name'],
                            'user_id'=>$id,
                            'user_name'=>$item['account_name'],
                            'seller_name'=>$item['account_name'],
                            'province_id'=>$supplier['province_id'],
                            'city_id'=>$supplier['city_id'],
                            'district'=>$supplier['county_id'],
                            'store_address'=>$supplier['province'].$supplier['city'].$supplier['county'].$supplier['address'],
                            'store_moneys'=>$item['money'],
                            'store_state'=>$supplier['store_tag'],
                            'store_time'=>$item['create_time']?strtotime($item['create_time']):null,
                            'store_logo'=>str_replace('https://xjt.zczmer.com','',M('img_info','xbt_')->where(['IMG_ID'=>$supplier['store_img_id']])->getField('IMG_PATH')),
                            'koudian'=>$supplier['substation_pect'],
                            'fast_flag'=>$supplier['line_type']==1?1:0,
                            'xbt_supplier_id'=>$item['account_id'],
                        ];
                        $store_id = M('store')->add($store);
                        $seller = [
                            'seller_name'=>$item['account_name'],
                            'user_id'=>$id,
                            'store_id'=>$store_id,
                            'is_admin'=>1,
                            'xbt_supplier_id'=>$item['account_id'],
                        ];
                         M('seller')->add($seller);
                    }
                }
                Db::commit(); //事务提交
                exit('success');
            }catch(Exception $e){
                Db::rollback();//事务回滚
                Log::record($e->getMessage(),'ERR');
                $errorNo[] = $item[0];
            }
        }
        exit;
    }

    public function saveGoodsClass(){
        $data = M('product_classify','xbt_')->where(array('TYPE'=>'substation','P_ID'=>0))->select();
        // exit(json_encode($data));
        foreach($data as $v){
            $img = M('img_info','xbt_')->where(['IMG_ID'=>$v['img_id']])->getField('IMG_PATH');
            // dump($img);exit;
            $insert = [
                'id'=>$v['classify_id'],
                'name'=>$v['classify_name'],
                'parent_id'=>0,
                'level'=>1,
                'sort_order'=>50,
                'image'=>str_replace('https://xjt.zczmer.com','',$img),
                'is_show'=>$v['status']==1?1:0,
                'CLASSIFY_ID'=>$v['classify_id']
            ];
            $id = M('goods_category')->add($insert);
            M('goods_category')->where(array('id'=>$id))->save(['parent_id_path'=>'0_'.$id]);
        }
        exit(json_encode($data));
    }
    public function saveGoodsClass2(){
        $parent = M('goods_category')->where(array('pid'=>0))->select();
        
        // exit(json_encode($parent));
        foreach($parent as $val){
            $data = M('product_classify','xbt_')->where(array('TYPE'=>'substation','P_ID'=>$val['classify_id']))->select();
            // exit(json_encode($data));
            foreach($data as $v){
                $img = M('img_info','xbt_')->where(['IMG_ID'=>$v['img_id']])->getField('IMG_PATH');
                // dump($img);exit;
                $insert = [
                    'id'=>$v['classify_id'],
                    'name'=>$v['classify_name'],
                    'parent_id'=>$val['id'],
                    'level'=>2,
                    'sort_order'=>50,
                    'image'=>str_replace('https://xjt.zczmer.com','',$img),
                    'is_show'=>$v['status']==1?1:0,
                    'CLASSIFY_ID'=>$v['classify_id']
                ];
                $id = M('goods_category')->add($insert);
                M('goods_category')->where(array('id'=>$id))->save(['parent_id_path'=>$val['parent_id_path'].'_'.$id]);
            }
        }
        exit(json_encode($data));
    }
    
    public function saveGoodsClass3(){
        $parent = M('goods_category')->where(array('parent_id'=>0))->select();
        
        // exit(json_encode($parent));
        foreach($parent as $val){
            $sec = M('goods_category')->where(array('parent_id'=>$val['id']))->select();
            // exit('123');
            // exit(json_encode($sec));
            foreach($sec as $child){
                // exit(json_encode($child));
                $data = M('product_classify','xbt_')->where(array('TYPE'=>'substation','P_ID'=>$child['classify_id']))->select();
                // exit(json_encode($data));
                foreach($data as $v){
                    $img = M('img_info','xbt_')->where(['IMG_ID'=>$v['img_id']])->getField('IMG_PATH');
                    // dump($img);exit;
                    $insert = [
                        'id'=>$v['classify_id'],
                        'name'=>$v['classify_name'],
                        'parent_id'=>$child['id'],
                        'level'=>3,
                        'sort_order'=>50,
                        'image'=>str_replace('https://xjt.zczmer.com','',$img),
                        'is_show'=>$v['status']==1?1:0,
                        'CLASSIFY_ID'=>$v['classify_id']
                    ];
                    $id = M('goods_category')->add($insert);
                    M('goods_category')->where(array('id'=>$id))->save(['parent_id_path'=>$child['parent_id_path'].'_'.$id]);
                }
            }
        }
        exit(json_encode($data));
    }

    public function saveStoreGoodsClass() {
        $where = [];
        $where['TYPE'] = ['eq','supplier'];
        $where['P_ID'] = ['neq',0];
        $data = M('product_classify','xbt_')->where($where)->select();
        // exit(json_encode($data));
        $insert = [];
        foreach($data as $v){
            $insert[] = [
                'cat_id'=>$v['classify_id'],
                'cat_name'=>$v['classify_name'],
                'parent_id'=>$v['p_id'],
                'store_id'=>$v['supplier_id'],
                'cat_sort'=>$v['classify_sort'],
                'is_show'=>$v['status']==1?1:0,
                // 'image'=>str_replace('https://xjt.zczmer.com','',M('img_info','xbt_')->where(['IMG_ID'=>$v['img_id']])->getField('IMG_PATH')),
            ];
        }
        $res = M('store_goods_class')->addAll($insert);
        
        exit(json_encode($res));
    }

    public function saveFollowGoods(){
        $where['ACTIVITY_ID'] = ['eq',0];
        $data = M('user_follow_product','xbt_')->where($where)->select();
        // exit(json_encode($data));
        $insert = [];
        foreach($data as $v){
            $insert[] = [
                'user_id'=>$v['account_id'],
                'goods_id'=>$v['product_id'],
                'add_time'=>$v['follow_time']?strtotime($v['follow_time']):null,
            ];
        }
        $res = M('goods_collect')->addAll($insert);
        
        exit(json_encode($res));
    }
    public function saveFollowStore(){
        $data = M('follow_store','xbt_')->alias('a')->field('a.*,b.nickname,c.store_name')
        ->join('ty_users as b on b.user_id=a.ACCOUNT_ID','left')
        ->join('ty_store as c on c.store_id=a.SUPPLIER_ID','left')
        ->select();
        // exit(json_encode($data));
        $insert = [];
        foreach($data as $v){
            $insert[] = [
                'user_id'=>$v['account_id'],
                'store_id'=>$v['supplier_id'],
                'add_time'=>$v['follow_time']?strtotime($v['follow_time']):null,
                'user_name'=>$v['nickname'],
                'store_name'=>$v['store_name'],
            ];
        }
        $res = M('store_collect')->addAll($insert);
        
        exit(json_encode($res));
    }

    public function saveBrand(){
        $status = [
            0=>1,
            1=>0,
            2=>2
        ];
        $where['SUBSTATION_ID'] = ['eq',4];
        $data = M('product_brand','xbt_')->where($where)->select();
        // exit(json_encode($data));
        $insert = [];
        foreach($data as $v){
            $insert[] = [
                'id'=>$v['brand_id'],
                'name'=>$v['brand_name'],
                'status'=>$status[$v['status']],
                'logo'=>$v['img_id']?str_replace('https://xjt.zczmer.com','',M('img_info','xbt_')->where(['IMG_ID'=>$v['img_id']])->getField('IMG_PATH')):'',
                'store_id'=>$v['supplier_id'],
                'sort'=>$v['brand_sort'],
            ];
        }
        $res = M('brand')->addAll($insert);
        exit(json_encode($res));
    }
}